package org.example.retry;

import java.util.concurrent.TimeUnit;

/**
 * 代理模式,使用循环的方式来实现重试
 */
public class RetryByLoop {
    private Handler handler;
    // 重试次数
    private Integer count = 0;
    // 最大重试次数
    private Integer maxCount = 0;
    // 重试时间间隔ms
    private Integer interval = 0;

    public RetryByLoop(Handler handler, Integer count, Integer interval) {
        this.handler = handler;
        this.maxCount = count;
        this.interval = interval;
    }

    /**
     * @param code
     * @return
     */
    public Boolean handler(Integer code) throws RetryException {
        Boolean result = false;
        while (true) {
            try {
                // 正常执行
                result = handler.handle(code);
                if (result) {
                    break;
                }
            } catch (BusiException retry) {
            } finally {
                // 到达重试次数
                if (++count >= maxCount) {
                    break;
                }
                // 重试
                try {
                    if (!result) {
                        TimeUnit.MILLISECONDS.sleep(interval);
                    }
                } catch (InterruptedException ignore) {}
            }
        }
        if (!result) {
            throw new RetryException("重试完成!,重试次数 "+count);
        }
        return result;
    }


}
